
#pragma once
#include <mutex>
#include <iostream>
#include "ThreadCache.hpp"
#include "PackageCache.hpp"
#include "ObjectPool.hpp"
//线程申请空间
void* ConcurrentAlloc(size_t size)
{
    if(size > Max_Byte)
    {
        //大于256KB，直接向PC中要内存
        size_t aligSize = SizeClass::RoundUP(size);
        size_t k = aligSize >> Pack_Shift;
        //直接加锁
        PackageCache::create()->_mutex.lock();
        Span* span = PackageCache::create()->NewSpan(k);
        PackageCache::create()->_mutex.unlock();
        //地址就是根据Pageid来进行转换的
        void* str = (void*)(span->_pageID << Pack_Shift); 
        return str;
    }else{
        if(PTLSThreadCache == nullptr)
        {
            //PTLSThreadCache = new ThreadCache;
            static ObjectPool<ThreadCache> Objectpool;
            Objectpool._Objmutex.lock();
            //这里多线程可能会出现错误，需要加锁
            PTLSThreadCache = Objectpool.New();
            Objectpool._Objmutex.unlock();
        }
        return PTLSThreadCache->Allocate(size);
    }
}

//线程释放空间
void ConcurrentFree(void* obj)
{
    assert(obj);
    Span* span = PackageCache::create()->MaptoSpan(obj);
    size_t size = span->_blocksize;
    if(size > Max_Byte)
    {
        //超过最大的256kb交给pc自己去处理
        //获取对应的span
        PackageCache::create()->_mutex.lock();
        PackageCache::create()->ReleasePackageSpan(span);
        PackageCache::create()->_mutex.unlock();
    }
    PTLSThreadCache->Deallocate(obj,size);
}